<?php
/**
 * Created by PhpStorm.
 * User: mt
 * Date: 2018/6/6
 * Time: 9:57
 */

namespace App\Handlers;

use App\Models\Traits\GameTypeTrait;

class CounterHandler
{
    use GameTypeTrait;
    private $game_type;



    public function handleData($game_data, $type)
    {
        $list = $game_data;
        $this->game_type = $this->game_types[$type];
        //$list = json_decode($game_data);
        if(!isset($list)){
            return false;
        }
       $this->handleList($list);
    }

    public function handleList($list)
    {
        foreach($list as $value)
        {
            $this->handleItem($value);
        }

    }

    public function handleItem($item)
    {
        $game = $this->game_type::find($item['question_id']);
        if(!$game->counter){
            //初始化数据记录
            $answers = explode("|", $game->answers);
            $count = count($answers);
            $list = [];
            for($i = 1; $i <= $count; $i ++)
            {
                $list[$this->options[$i]] = 0;
            }
        } else {
            $list = json_decode($game->counter, true);
        }
        foreach($list as $key => $value)
        {
            if($item['currentChoose'] == $key)
            {
                $list[$key] ++;
            }
        }
        $game->counter = json_encode($list);
        if($item['isCorrect']){
            $game->correct_count++;
        }
        $game->save();
    }

}